package io.gitee.kotle.android.library.banner.impl.banner

import android.animation.ValueAnimator
import android.graphics.Rect
import android.view.View
import android.view.ViewGroup
import android.view.animation.Interpolator
import android.view.animation.LinearInterpolator
import androidx.annotation.LayoutRes
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import io.gitee.kotle.android.adapter.refreshList
import io.gitee.kotle.android.delegate.unsafeLazy
import io.gitee.kotle.android.library.banner.IBanner
import io.gitee.kotle.android.library.banner.impl.ybanner.transformer.ScaleInTransformer
import io.gitee.kotle.android.utils.*

/**
 *
 * 描述：
 *
 * 创建人：jiale.wei
 * 创建时间：2021/12/13 4:15 下午
 *
 */
open class BannerViewHelper<Data : IBanner.BannerData>(
    private val container: ViewGroup,
    private val lifecycleOwner: LifecycleOwner?
) {
    private val context
        get() = container.context

    val adapter by unsafeLazy { BannerAdapter(this) }

    val viewPage = ViewPager2(context)

    val recyclerView: RecyclerView by unsafeLazy { viewPage.getChildAt(0) as RecyclerView }

    init {
        viewPage.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
            override fun onViewAttachedToWindow(v: View) {
                tickTask.onStart()
            }

            override fun onViewDetachedFromWindow(v: View) {
                tickTask.onStop()
            }
        })
        viewPage.offscreenPageLimit = 3
        viewPage.setPageTransformer(ScaleInTransformer())
        viewPage.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)
                if (state == ViewPager2.SCROLL_STATE_IDLE) {
                    checkEnableAutoStroll()
                } else {
                    if (!anim.isRunning && !viewPage.isFakeDragging) {//不是动画导致的中断，结束任务
                        stopTick()
                    }
                }
            }

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                val index = position % adapter.currentList.count()
                listener?.onBannerSelected(adapter.currentList[index], index)
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
            }
        })
        container.addView(
            viewPage, ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT,
            )
        )
        viewPage.adapter = adapter
    }

    /**
     * 监听器
     */
    var listener: IBanner.Listener<Data>? = null

    /**
     * 是否允许自动滚动
     */
    var enableAutoScroll = true
        set(value) {
            field = value
            if (value) {
                checkEnableAutoStroll()
            } else {
                stopTick()
                anim.cancel()
                viewPage.endFakeDrag()
            }
        }

    /**
     * 停留时长
     */
    var stayDuration: Long = 5000L
        set(value) {
            field = value
            tickTask.time = tickTaskTime
            tickTask.delayStartDuration = tickTaskTime
        }

    /**
     * 只响应当前显示的item
     */
    var canOnlyClickCurrentItem: Boolean = true

    /**
     * 外间距
     */
    var itemMargin: Rect? = null


    /**
     * 内间距
     */
    var itemPadding: Rect? = null
        set(value) {
            field = value
            viewPage.setPadding(
                value?.left ?: 0,
                value?.top ?: 0,
                value?.right ?: 0,
                value?.bottom ?: 0,
            )
            viewPage.clipToPadding = false
            viewPage.clipChildren = false
        }

    /**
     * 自定义的item布局
     */
    @LayoutRes
    var customItemLayoutRes: Int? = null

    /**
     * 设置动画插值器
     */
    var animInterpolator: Interpolator = LinearInterpolator()

    /**
     * 循环次数
     * <=0 无限轮询
     */
    var repeatCount = -1

    /**
     * 动画时长
     */
    var animDuration: Long = 1000L
        set(value) {
            field = value
            anim.duration = value
            tickTask.time = tickTaskTime
            tickTask.delayStartDuration = tickTaskTime
        }

    /**
     * 总的间隔
     */
    private val tickTaskTime
        get() = stayDuration + animDuration

    private var tickTask = TickTask(tickTaskTime) {
        startAutoScroll()
    }.also {
        it.delayStartDuration = tickTaskTime
    }


    init {
        setLifecycle(lifecycleOwner)
    }

    private var hadDragValue: Float = 0f
    private val anim = ValueAnimator.ofFloat().also {
        it.duration = animDuration
        it.addUpdateListener { anim ->
            val value = anim.animatedValue as Float
            val dragValue = value - hadDragValue
            hadDragValue = value
            if (!viewPage.fakeDragBy(dragValue)) {
                anim.cancel()
                viewPage.endFakeDrag()
            }
            if (anim.animatedFraction == 1f) {
                viewPage.endFakeDrag()
            }
        }
    }

    private fun startAutoScroll() {
        anim.cancel()
        if (!enableAutoScroll ||
            adapter.itemCount - 1 == viewPage.currentItem//已经滚动到最后一个
        ) {
            stopTick()
            viewPage.endFakeDrag()
            return
        }
        val endValue = if (viewPage.orientation == ViewPager2.ORIENTATION_HORIZONTAL) {
            recyclerView.width.toFloat()
        } else {
            recyclerView.width.toFloat()
        }
        if (endValue > 0f) {
            startScrollAnim(endValue)
        }
    }

    /**
     * 设置集合
     */
    fun setDatas(datas: List<Data>?, startIndex: Int = 0) {
        adapter.refreshList(datas)
        initCurrentItem(datas?.count(), startIndex)
        checkEnableAutoStroll()
    }

    /**
     * 设置什么周期
     */
    fun setLifecycle(lifecycleOwner: LifecycleOwner?) {
        lifecycleOwner?.lifecycle?.addObserver(tickTask)
    }

    /**
     * 定位到当前位置
     */
    private fun initCurrentItem(dataCount: Int?, startIndex: Int) {
        if (dataCount == null || dataCount == 0) {
            return
        }
        val currentIndex = adapter.itemCount / 2
        val index = currentIndex % dataCount
        viewPage.setCurrentItem(currentIndex - index + startIndex, false)
    }


    /**
     * 延时运行轮训任务
     */
    private fun checkEnableAutoStroll() {
        //双重检查是否可以自动滚动
        if (enableAutoScroll) {
            startTick()
        }
    }

    /**
     * 滚动动画逻辑
     */
    private fun startScrollAnim(endValue: Float) {
        if (viewPage.scrollState != ViewPager2.SCROLL_STATE_IDLE || !viewPage.beginFakeDrag()) {
            startTick()
            return
        }
        anim.setFloatValues(0f, -endValue)
        anim.interpolator = animInterpolator
        hadDragValue = 0f
        anim.start()
    }

    private fun startTick() {
        if (tickTask.isRunning) {
            return
        }
        tickTask.start()
    }

    private fun stopTick() {
        if (!tickTask.isRunning) {
            return
        }
        tickTask.cancel()
    }

    /**
     * 清理工作处理
     */
    fun onClear() {
        stopTick()
        anim.cancel()
    }
}